package com.chuangjian.hire.config;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.common.SSOConstants;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.kisso.web.handler.KissoDefaultHandler;
import com.baomidou.kisso.web.handler.SSOHandlerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


public class SSOSpringInterceptor extends HandlerInterceptorAdapter {
    private static final Logger log = LoggerFactory.getLogger(com.chuangjian.hire.config.SSOSpringInterceptor.class);
    private SSOHandlerInterceptor handlerInterceptor;

    public SSOSpringInterceptor() {
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            Login login = (Login) method.getAnnotation(Login.class);

            if (login == null || login.action() == Action.Skip) {
                return true;
            }

            SSOToken ssoToken = SSOHelper.getSSOToken(request);
            if (ssoToken == null) {
                if (HttpUtil.isAjax(request)) {
                    this.getHandlerInterceptor().preTokenIsNullAjax(request, response);
                    return false;
                }

                if (this.getHandlerInterceptor().preTokenIsNull(request, response)) {
                    log.debug("logout. request url:" + request.getRequestURL());
                    SSOHelper.clearRedirectLogin(request, response);
                }

                return false;
            }

            request.setAttribute(SSOConstants.SSO_TOKEN_ATTR, ssoToken);
        }

        return true;
    }

    public SSOHandlerInterceptor getHandlerInterceptor() {
        return (SSOHandlerInterceptor) (this.handlerInterceptor == null ? KissoDefaultHandler.getInstance() : this.handlerInterceptor);
    }

    public void setHandlerInterceptor(SSOHandlerInterceptor handlerInterceptor) {
        this.handlerInterceptor = handlerInterceptor;
    }
}
